package com.my.simple.service.auth;

import com.my.simple.common.util.EHCacheUtils;
import com.my.simple.entity.auth.Operation;
import com.my.simple.repository.dao.AuthOperationDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.my.simple.common.constant.CacheConstant.CACHE_PERMISSION_ACTION;

@Service
public class OperationServiceImpl implements OperationService {
    @Autowired
    private AuthOperationDao operationDao;


    @Override
    public void addOperation(Operation operation) {
        operationDao.addOperation(operation);
    }

    @Override
    public List<Operation> getAllOperation() {
        return operationDao.getAllOperation();
    }

    @Override
    public Operation getOperationById(Integer operationId) {
        return operationDao.getOperationById(operationId);
    }


    @Override
    public void deleteOperationById(Integer operationId) {
        operationDao.deleteOperationById(operationId);
    }

    @Override
    public void updateOperation(Operation operationItem) {
        operationDao.updateOperation(operationItem);
    }

    @Override
    public List<Operation> getNeedPermissionOperation() {
        List<Operation> operationEntityList = new ArrayList<>();
        //get from cache first
        Object obj = EHCacheUtils.get(CACHE_PERMISSION_ACTION);

        if (obj != null) {
            operationEntityList = (List<Operation>) obj;

        } else {
            //get from db
            operationEntityList = operationDao.getNeedPermissionOperation();
            EHCacheUtils.put(CACHE_PERMISSION_ACTION, operationEntityList);
        }

        return operationEntityList;
    }

    @Override
    public List<Operation> getOperationByRoleId(Integer roleId) {
        List<Operation> operationEntityList = new ArrayList<>();
        if (roleId != null) {
            operationEntityList = operationDao.getOperationByRoleId(roleId);
        }
        return operationEntityList;
    }

    @Override
    public List<Operation> getOperationByRoleIdList(List<Integer> roleIdList) {
        List<Operation> operationEntityList = new ArrayList<>();
        if (roleIdList != null && roleIdList.isEmpty()) {
            operationEntityList = operationDao.getOperationByRoleIdList(roleIdList);
        }
        return operationEntityList;
    }

}
